package zju.dgm.webcontroller;


import MiniSQL.JDBCUtils;
import com.alibaba.fastjson.JSONObject;
import org.apache.curator.framework.CuratorFramework;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import zju.dgm.dto.ServerInfo;
import zju.dgm.service.distsqlservice.DistSqlUtilProvider;
import zju.dgm.service.region.RegionUtilProvider;
import zju.dgm.sqlcfg.JdbcHandle;
import zju.dgm.util.SyncUtil;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Map;

/**
 * @author lzy
 */
@RestController
public class SQLController {
    static final Logger logger = LoggerFactory.getLogger(SQLController.class);

    @Autowired
    private JdbcHandle jdbcHandle;

    @Autowired
    private RegionUtilProvider regionUtilProvider;


    @Autowired
    private DistSqlUtilProvider distSqlUtilProvider;


    @PostMapping("/sqljson")
    public String handleSQL(@RequestBody JSONObject jsonObject) throws Exception {
        logger.info("接到一个sql请求:{}", jsonObject.toJSONString());
        String table = jsonObject.getString("table");
        Integer version = jsonObject.getInteger("version");
        Integer type = jsonObject.getInteger("type");
        String sql = jsonObject.getString("sql");
        JSONObject rst = new JSONObject();
        Map regionMap = regionUtilProvider.getRegionMap();
        if (!regionMap.containsKey(table) && type != DistSqlUtilProvider.CREATE) {
            rst.put("sqlResult", "no table named " + table);

        } else {
            rst.put("sqlResult", distSqlUtilProvider.distSql(table, type, sql));
            rst.put("cacheMap", regionUtilProvider.checkVersion(version));
        }
        return rst.toJSONString();

    }

    @PostMapping("/serverInfo")
    public ServerInfo getServerInfo() {
        return SyncUtil.serverInfo;
    }


}
